<template>
    <div :class="$style.box">
        <el-form-item
            :label="selectProps.title"
            :prop="curNodePath"
            :class="$style.elFormItem"
            :rules="[
                {
                    validator(rule, value, callback) {
                        const validProperties = ['imgUrl', 'imgLink'];

                        // 针对叶子节点做校验
                        let errors = [];
                        const isValidate = validProperties.every(item => {
                            errors = schemaValidate.validateFormDataAndTransformMsg({
                                formData: value[item],
                                schema: $props.schema.properties[item],
                                customFormats: $props.customFormats,
                                errorSchema: $props.errorSchema[item],
                                required: $props.schema.required.includes(item),
                                propPath: $props.curNodePath
                            });
                            return errors.length <= 0;
                        });

                        if (isValidate) return callback();

                        return callback(errors[0].message);
                    },
                }
            ]"
            :required="elItemRequired"
        >
            <div
                v-if="selectProps.description"
                :class="$style.description"
                v-html="selectProps.description"
            ></div>
            <div :class="$style.formItem">
                <div
                    :class="$style.uploadBox"
                    @click="selectImg"
                >
                    <img
                        v-if="imgUrl"
                        :src="imgUrl"
                        alt=""
                        style="max-width: 100%;max-height: 100%;"
                    >
                    <i
                        v-else
                        class="el-icon-plus"
                    ></i>
                </div>
                <el-input
                    v-model="imgLink"
                    :class="$style.input"
                    :placeholder="placeholder"
                    size="medium"
                ></el-input>
            </div>
        </el-form-item>
        <el-dialog
                title="提示"
                :visible.sync="dialogVisible"
                width="80%"
                :before-close="handleClose">

            <el-upload class="uploader" ref="Imagesupload" :action="imageAction" :show-file-list="true" :headers="headers" multiple :limit="1" :on-exceed="handleImagesExceed" :on-success="handleImagesSuccess" :on-remove="handleImagesRemove" :before-upload="beforeImagesUpload" :file-list="ImagesfileList" :auto-upload="false">
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitImagesUpload">上传到服务器</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
            </el-upload>

            <vue-select-image
                    :dataImages="dataImages"
                    @onselectimage="onSelectImage">
            </vue-select-image>
            <div class="block">
                <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="paginate.current" hide-on-single-page :page-sizes="paginate.sizes" :page-size="paginate.limit" :layout="paginate.layout" :total="paginate.total">
                </el-pagination>
            </div>
            <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span>
        </el-dialog>
    </div>
</template>

<script>
    // 覆盖默认field 做个性商品选择和链接输入
import {
    fieldProps,
    vueUtils,
    formUtils,
    schemaValidate
} from '@lljj/vue-json-schema-form';
import VueSelectImage from 'vue-select-image'
import {getToken} from '../../../../utils/auth';
require('vue-select-image/dist/vue-select-image.css')
export default {
    name: 'LinkImgField',
    components: { VueSelectImage },
    props: {
        ...fieldProps,
        fieldProps: {
            type: null,
            default: null
        }
    },
    data() {
        return {
            schemaValidate,
            vueUtils,
            dialogVisible: false,
            imageSelected: null,
            dataImages:[],
            paginate: {
                sizes: [10, 15, 20, 30, 50],
                limit: 10,
                layout: 'total, sizes, prev, pager, next, jumper',
                current: 0,
                total: 0
            },
            queryParam: {},
            imageAction: process.env.VUE_APP_BASE_API + '/upload/image',
            formFieldsData:[],
            headers: {
                authorization: 'Bearer ' + getToken()
            },
        };
    },
    created() {
    },
    computed: {
        elItemRequired() {
            // 配置了 required 的属性提示小红点
            return this.schema.required.length > 0;
        },
        placeholder() {
            const imgLinkOptions = formUtils.getUiOptions({
                schema: this.schema.properties.imgLink,
                uiSchema: this.uiSchema.imgLink || {}
            });
            return imgLinkOptions.placeholder || '请输入合法的链接';
        },
        selectProps() {
            return formUtils.getUiOptions({
                schema: this.schema,
                uiSchema: this.uiSchema
            });
        },
        curValue() {
            return vueUtils.getPathVal(this.rootFormData, this.curNodePath);
        },
        imgUrl: {
            get() {
                return this.curValue.imgUrl;
            },
            set(value) {
                vueUtils.setPathVal(this.rootFormData, vueUtils.computedCurPath(this.curNodePath, 'imgUrl'), value);
            }
        },
        imgLink: {
            get() {
                return this.curValue.imgLink;
            },
            set(value) {
                vueUtils.setPathVal(this.rootFormData, vueUtils.computedCurPath(this.curNodePath, 'imgLink'), value);
            }
        },
        AttachmentsModel() {
            return this.$store.$db().model('attachments');
        },
        allAttachments() {
            return this.$store.$db().model('attachments').all();
        },
        ImagesfileList: {
            get: function () {
                if (this.formFieldsData.Images) {
                    return JSON.parse(this.formFieldsData.Images);
                } else {
                    return [];
                }
            },
            set: function (newValue) {
            }
        },
    },
    methods: {
        selectImg() {
            this.getList();
            this.dialogVisible = true;
        },
        /*   onSelectImage(event) {
              console.log(event);
              this.$message.success('选择图片成功，随机一个图片');
              var el = event.currentTarget;
              console.log(el);
              alert("当前对象的内容："+el.innerHTML);
          },*/
         onSelectImage: function (data) {
              console.log('fire event onSelectImage: ', data);
              this.imageSelected = data;
              this.imgUrl = data.src;
          },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                    done();
                })
                .catch(_ => {});
        },
        handleSizeChange(val) {
            this.handlePaginateParams(val)
        },
        handleCurrentChange(val) {
            this.handlePaginateParams(0, val)
        },
        // 处理分页参数
        handlePaginateParams(limit = 0, page = 0) {
            if (limit) {
                this.queryParam.limit = limit
                this.paginate.limit = limit
            }
            if (page) {
                this.queryParam.page = page
                this.paginate.current = page
            }
            this.getList()
        },
        handlePaginateResponse(response) {
            if (response.limit !== undefined) {
                this.paginate.total = response.count
                this.paginate.limit = response.limit
                this.paginate.current = response.current
            }
        },
        // 列表请求
        async getList(params = null) {
            const query = params ? params : this.queryParam;

            if(params){
                Object.keys(params).forEach((k) => {
                    this.queryParam[k] = params[k];
                })
            }
            console.log('params');
            console.log(params);
            console.log('getList');
            console.log(query);
            const result = await this.AttachmentsModel.fetchByToken(query);
            console.log('result');
            console.log(result.response.data);
            this.handlePaginateResponse(result.response.data);
            this.dataImages =  this.allAttachments;
        },
        beforeImagesUpload (file) {
            const image = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/gif';
            if (!image) {
                this.$message.error('只支持 jpg/jpeg/png/gif 格式!');
            }
            let isLtSize = false;
            isLtSize = file.size / 1024 / 1024 < 5;
            if (!isLtSize) {
                this.$message.error('最大支持 5MB!');
            }
            return image && isLtSize;
        },
        handleImagesSuccess (response, file, fileList) {
            let filesData = [];
            fileList.forEach(function (item, index) {
                if (item.url) {
                    filesData.push({
                        'name': item.name,
                        'url': item.url
                    });
                } else {
                    if (response.data) {
                        filesData.push({
                            'name': item.name,
                            'url': response.data
                        });
                    }
                }
            });
            this.formFieldsData.Images = JSON.stringify(filesData);
            this.ImagesfileList = fileList;
        },
        handleImagesExceed (files, fileList) {
            this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        submitImagesUpload () {
            this.$refs.Imagesupload.submit();
        },
        handleImagesRemove (file, fileList) {
            let filesData = [];
            fileList.forEach(function (item, index) {
                if (item.url) {
                    filesData.push({
                        'name': item.name,
                        'url': item.url
                    });
                }
            });
            this.formFieldsData.Images = JSON.stringify(filesData);
        },
    }
};
</script>

<style module>
    @import 'demo-common/css/variable.css';
    .box {
        :global {
            .el-form-item.is-error {
                :local {
                    .uploadBox {
                        color: #F56C6C;
                    }
                }
            }
        }
    }
    :global {
        .arrayOrderList_item {
            :local {
                .elFormItem {
                    margin-bottom: 0;
                }
            }
        }
    }
    .formItem {
        align-items: center;
        display: flex;
    }
    .input {
        flex: 1;
        margin-left: 15px;
    }
    .description {
        font-size: 12px;
        line-height: 20px;
        margin-bottom: 10px;
        color: var(--color-text-light)
    }
    .uploadBox {
        cursor: pointer;
        width: 80px;
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #e2e2e2;
    }
</style>
